package com.sun.androidexerciseproject.function.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by Steven on 2016/7/21 0021.
 */

public class TestDao {
    private WeatherHelper mWeatherHelper;

    public TestDao(Context context) {
        mWeatherHelper = new WeatherHelper(context);
    }

    public void insert(int id, String name, String city) {
        SQLiteDatabase db = mWeatherHelper.getWritableDatabase();
        db.beginTransaction();
        ContentValues contentValues = new ContentValues();
        contentValues.put("Id", id);
        contentValues.put("Name", name);
        contentValues.put("City", city);
        db.insertOrThrow(WeatherHelper.TABLE_NAME, null, contentValues);
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    public boolean isDataExist() {
        SQLiteDatabase db = null;
        Cursor query = null;
        try {
            db = mWeatherHelper.getReadableDatabase();
            query = db.query(WeatherHelper.TABLE_NAME, new String[]{"Id"}, null, null, null, null, null);
            if (query.moveToFirst()) {
                int count = query.getInt(0);
                if (count > 0) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != query) {
                query.close();
            }
            if (null != db) {
                db.close();
            }
        }

        return false;
    }

    public void init() {
        SQLiteDatabase db = null;
        try {
            db = mWeatherHelper.getWritableDatabase();
            db.beginTransaction();
            db.execSQL("insert into " + WeatherHelper.TABLE_NAME + " values(22,'Zhang san','tangshan')");
            db.execSQL("insert into " + WeatherHelper.TABLE_NAME + " values(33,'li san','beijing')");
            db.execSQL("insert into " + WeatherHelper.TABLE_NAME + " values(232,'wang san','shenzhen')");
            db.execSQL("insert into " + WeatherHelper.TABLE_NAME + " values(332,'sun san','guangzhong')");
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != db) {
                db.endTransaction();
                db.close();
            }
        }
    }
}
